package com.kit.data.kitopeso.device.data

import android.Manifest
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import com.google.gson.Gson
import com.kit.data.kitopeso.base.BaseParams
import com.kit.data.kitopeso.device.util.gzipString

class AppInfo(val context: Context) {

    fun fetch(): String? {
        return try {
            val array = arrayOf(
//                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE
            )

            val flags = PackageManager.GET_ACTIVITIES or PackageManager.GET_META_DATA
            val packages = context.packageManager.getPackagesHoldingPermissions(array, flags)

            val appList = mutableListOf<HashMap<String, Any>>()
            for (packageInfo in packages) {
                val appInfo = packageInfo.applicationInfo

                if (appInfo != null) {
                    if (appInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0) continue
                }

                val appName = appInfo?.loadLabel(context.packageManager).toString()
                val appVersionCode = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                    packageInfo.versionCode.toString()
                } else {
                    packageInfo.longVersionCode.toString()
                }

                val jsonObject = HashMap<String, Any>().apply {
                    put("appType", 0)
                    put("appName", appName)
                    put("appVersionCode", appVersionCode)
                    if (appInfo != null) {
                        put("dataPath", appInfo.dataDir ?: "")
                    }
                    if (appInfo != null) {
                        put("sourcePath", appInfo.sourceDir ?: "")
                    }
                    put("appPackageName", packageInfo.packageName)
                    put("appVersionName", packageInfo.versionName ?: "")
                    put("installTime", packageInfo.firstInstallTime.toString())
                    put("lastTime", packageInfo.lastUpdateTime.toString())
                    put("version", BaseParams.getVersion(context))
                    if (appInfo != null) {
                        put("flags", appInfo.flags.toString())
                    }
                }

                appList.add(jsonObject)
            }

            Gson().toJson(appList).trim().gzipString()

        } catch (e: Exception) {
            null
        }
    }
}